package com.sample.sampleproj;

import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.sample.sampleproj.ListViewaActivity;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;
  

public class SampleprojActivity extends Activity implements OnClickListener {
   
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);// activity loads its UI from the XML file main.xml. 
       
        setContentView(R.layout.main); //to display it as the content for the Activity UI. 

        final Button btn1 = (Button) findViewById(R.id.Search);//R.id.button_id);
        btn1.setText("Search");
        btn1.setOnClickListener(this);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);//Drop-Down menu created in the android app
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.planets_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//To display all the options available in the drop-down menu ..the option are given Strings.xml
        spinner.setAdapter(adapter);
        
        
	}
	
   
	
         public void onClick(View v){
        	
        	 final EditText lat= (EditText) findViewById(R.id.latvalue);//the text field created in android app
        	
        		Toast.makeText(this, lat.getText(), Toast.LENGTH_LONG).show();
        		final EditText lon= (EditText) findViewById(R.id.lonvalue);
        		Toast.makeText(this, lon.getText(), Toast.LENGTH_LONG).show();
        		
        	
        		try{
        			Spinner spinner = (Spinner) findViewById(R.id.spinner);
        			 ArrayList<BasicNameValuePair> nvp= new ArrayList<BasicNameValuePair>(3);//array to store values 
                     nvp.add(new BasicNameValuePair("Cat", String.valueOf(spinner.getSelectedItem())));//Converts the form value to a string
                     nvp.add(new BasicNameValuePair("latitude", String.valueOf(lat.getText())));
                     nvp.add(new BasicNameValuePair("longitude",String.valueOf(lon.getText())));
        			URL url = new URL("http://204.232.203.10/mobile-db/User1.php"); 
        			     url.openConnection(); 
        		     HttpClient httpclient = new DefaultHttpClient();
        		     HttpPost httppost = new HttpPost("http://204.232.203.10/mobile-db/User1.php");
        		     httppost.setEntity(new UrlEncodedFormEntity(nvp)); //to send namevaluepair array values from the android form to User1.php
        		     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();//To avoid the networkonmainthreadException(supposed To send http request asynchronusly ,if not the operation is done on the main thread and an exception is thrown)
        		     StrictMode.setThreadPolicy(policy);
        		     
        		   String rest= httpclient.execute(httppost, finishTranslation);
        		   System.out.println(rest);
        		   Document doc=XMLfunctions.XMLfromString(rest);
        		   NodeList nodes = doc.getElementsByTagName("Park");
        		   
        		   //String x="Hello Android";
        		   Intent intent = new Intent(SampleprojActivity.this,ListViewActivity.class);
        		   
           	       intent.putExtra("rest",rest);
        		  // startActivity(intent);
        		   startActivityForResult(intent,1);
        		   
        		   
        		   ListView lv= (ListView)findViewById(R.id.listview);
       	        String[] from = new String[] {"P_Name", "P_City"};
       	                int[] to = new int[] { R.id.item1, R.id.item2 };
       	           List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
       	           for(int i = 0; i < nodes.getLength(); i++)
       	           {    
       	        	      HashMap<String, String> map = new HashMap<String, String>();
       	        	       map.put("P_Name", "P_Name:" + doc.getElementsByTagName("P_Name").item(i).getChildNodes().item(0).getNodeValue());
       	        	       map.put("P_City", "P_City:" +doc.getElementsByTagName("P_City").item(i).getChildNodes().item(0).getNodeValue());
       	        	      
       	        	       fillMaps.add(map);
       	           }
       	        	       SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.list_item, from, to);
       	        	     
       	        	               lv.setAdapter(adapter);

        		     //Document XMLfromString1(result);
 //       		Intent intent = new Intent(this,ListActivity.class);
   //     	        startActivity(intent);
        	      
        		     }catch(Exception e){
        		         Log.e("log_tag", "Error in http connection"+e.toString());
        		         Toast.makeText(this, "ERROR IN CONN", Toast.LENGTH_LONG).show();
        		    }
         
         }
        		final ResponseHandler<String> finishTranslation = new ResponseHandler<String>() 

        	{
        		    public String handleResponse(
        		            HttpResponse response) throws ClientProtocolException, IOException 
        		    {
        		    	Log.e("log_tag","After response handling");
        		    	HttpEntity entity = response.getEntity();//gets the response from User1.php
        		        if (entity != null) 
        		        {  
        		            String res = EntityUtils.toString(entity);//Converts the response to a String
        		            System.out.println(res);
        		            System.out.println("ParsingXML");
                			// Document doc = null;
                			 //DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                			 //try {
                		       //      DocumentBuilder db = dbf.newDocumentBuilder();
                                 //    InputSource is = new InputSource();
                                   //  is.setCharacterStream(new StringReader(res));
                                     // doc = db.parse(is);
                                      //System.out.println(doc);
                                      //System.out.println("ParsedXML");
                	              //} catch (ParserConfigurationException e) 
                	                //  {     
                	            	  //      System.out.println("XML parse error: " + e.getMessage());
                			               // return null;
                                      //} catch (SAXException e)
                                       // {
                			             //System.out.println("Wrong XML file structure: " + e.getMessage());
                			             //return null;
                			            //} catch (IOException e) 
                			              // {         
                			              //    System.out.println("I/O exeption: " + e.getMessage());
                			                  //return null;
                			                //}
                			    //NodeList nodes = doc.getElementsByTagName("Park");
                                //System.out.println("The length of the xml is "+nodes.getLength());
                                
                		        //for(int i=0;i<nodes.getLength();i++)
                		        //{ 
                		        	//Element e = (Element)nodes.item(i);
                		        	//System.out.println(XMLfunctions.getValue(e, "P_id"));
                		         // System.out.println(doc.getElementsByTagName("P_id").item(i).getChildNodes().item(0).getNodeValue());
                		         // System.out.println(doc.getElementsByTagName("P_Name").item(i).getChildNodes().item(0).getNodeValue());
                		          //System.out.println(doc.getElementsByTagName("P_City").item(i).getChildNodes().item(0).getNodeValue());
                		          //System.out.println(doc.getElementsByTagName("P_State").item(i).getChildNodes().item(0).getNodeValue());
                		          //System.out.println(doc.getElementsByTagName("P_Location").item(i).getChildNodes().item(0).getNodeValue());
                		        //}
                		  
                		     // Intent intent = new Intent(this,SampleprojActivity.class);
                		        //startActivity(intent);
                		      return res;
        		        } 
        		        else{
        		        	return null;
        		        }
        		    }
        	
						
        				
        		};

}
  
